import { Component,OnInit,Output,Input,EventEmitter } from '@angular/core';

declare var is:any;
declare var utils:any;

@Component({
  selector:'pagination-component',
  templateUrl:'pagination.component.html'
})
export class PaginationComponent implements OnInit {
   //分页通用组件
  @Input() pageModel:any;
  @Output() updatePageDatas:EventEmitter<any> = new EventEmitter();

  private isFirstPage:boolean;
  private isLastPage:boolean;
  private pageCount:number;

  constructor() {
    this.isFirstPage = false;
    this.isLastPage = false;
  }

  ngOnInit() {
    this.pageModel = {currentPageNum:1,pageNumber:0,pageCount:0};
  }

  extractPageData() {

    if (this.pageModel.currentPageNum === 1) {
      this.isFirstPage = true;
    } else {
      this.isFirstPage = false;
    }

    if (this.pageModel.currentPageNum === this.pageModel.pageNumber) {
      this.isLastPage = true;
    } else {
      this.isLastPage = false;
    }

    this.pageCount = this.pageModel.pageNumber;
    if(this.pageCount){
      this.pageCount = 1;
    }
  }

  evalPageNumber() {
    this.pageModel.currentPageNum = eval(this.pageModel.currentPageNum + "");
  }

  previousPage() {
    if (!is.numeric(this.pageModel.currentPageNum)) {
      return;
    }

    this.evalPageNumber();
    if (this.pageModel.currentPageNum <= 1 || this.pageModel.currentPageNum > this.pageModel.pageNumber) {
      return;
    }

    this.pageModel.currentPageNum = this.pageModel.currentPageNum - 1;
    this.extractPageData();
    this.updatePageDatas.emit();
  }

  nextPage() {
    if (!is.numeric(this.pageModel.currentPageNum)) {
      return;
    }

    this.evalPageNumber();
    if (this.pageModel.currentPageNum <= 0 || this.pageModel.currentPageNum >= this.pageModel.pageNumber) {
      return;
    }

    this.evalPageNumber();
    this.pageModel.currentPageNum = this.pageModel.currentPageNum + 1;
    this.extractPageData();
    this.updatePageDatas.emit();
  }

  jumpPage() {
    if (!is.numeric(this.pageModel.currentPageNum)) {
      return;
    }

    this.evalPageNumber();

    if (this.pageModel.currentPageNum <= 0) {
        this.pageModel.currentPageNum = 1;
        this.extractPageData();
        this.updatePageDatas.emit();
    }

    if(this.pageModel.currentPageNum > this.pageModel.pageNumber){
      this.pageModel.currentPageNum = this.pageModel.pageNumber;
      this.extractPageData();
      this.updatePageDatas.emit();
    }

    this.extractPageData();
    this.updatePageDatas.emit();
  }
}
